/*
 * Created on 2005-6-3
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package cn.newtest.common.dbf;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import cn.newtest.common.exception.ApplicationException;

import org.apache.commons.lang.StringUtils;

public class StringToXLS {
	String spliter = ",", rowSpliter = "\r\n";

	public void setSpliter(String v) {
		spliter = v;
	}

	public void setRowSpliter(String v) {
		rowSpliter = v;
	}

	public boolean stringToXLS(String[] titles, StringBuffer str,
			String fileName, int specialOP) throws ApplicationException {
		boolean success = true;
		String[] fields = null;
		JDBField[] jdbFields = null;
		if (titles != null) {
			jdbFields = getField(titles);
		} else {
			return false;
		}
		ArrayList dbData = format(str, titles.length, specialOP, jdbFields);
		try {
			writeFile(fileName, jdbFields, dbData);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new ApplicationException(ex.getMessage());
		}
		return success;
	}

	public boolean stringToXLS(String[] titles, StringBuffer str,
			OutputStream out, int specialOP) throws ApplicationException {
		boolean success = true;
		String[] fields = null;
		JDBField[] jdbFields = null;
		if (titles != null) {
			jdbFields = getField(titles);
		} else {
			return false;
		}
		ArrayList dbData = format(str, titles.length, specialOP, jdbFields);
		try {
			writeFile(out, jdbFields, dbData);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new ApplicationException(ex.getMessage());
		}
		return success;
	}

	public ArrayList format(StringBuffer str, int len, int specialOP,
			JDBField[] jdbFields) {
		ArrayList alist = new ArrayList();
		String[] rows = StringUtils.split(str.toString(), rowSpliter);
		String[] data = null;
		Object[] tmp = null;
		for (int i = 0; i < rows.length; i++) {
			tmp = new Object[len];
			/*
			 * if(rows[i].endsWith(spliter)){ rows[i] = rows[i]+" "; }
			 */
			data = StringUtils.split(rows[i], spliter);
			if (specialOP == 0) {
				for (int j = 0; j < len; j++) {
					// (c != 'C' && c != 'N' && c != 'L' && c != 'D' && c != 'F'
					// && c !='B')
					if (jdbFields[j].getType() == 'N') {
						tmp[j] = new Integer(data[j]);
					} else if (jdbFields[j].getType() == 'F') {
						tmp[j] = new Float(data[j]);
					} else if (jdbFields[j].getType() == 'B') {
						tmp[j] = new Double(data[j]);
					} else if (jdbFields[j].getType() == 'C') {
						int fieldLen = jdbFields[j].getLength();
						if (fieldLen - 1 < data[j].length()) {
							tmp[j] = data[j].substring(0, fieldLen - 1);
						} else {
							tmp[j] = data[j];
						}
					} else if (jdbFields[j].getType() == 'D') {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
						try {
							tmp[j] = sdf.parse(data[j]);// 跨过名称代码
						} catch (Exception ex) {
							ex.printStackTrace();
							tmp[j] = new Date();
						}
					} else if (jdbFields[j].getType() == 'L') {
						tmp[j] = new Boolean(data[j]);// 跨过名称代码
					} else {
						tmp[j] = data[j];// 跨过名称代码
					}

				}
			} else if (specialOP == 1) {// 特殊操作，企调景气专业
				tmp[0] = "";
				tmp[1] = "";
				tmp[2] = "";
				tmp[3] = data[1];
				tmp[4] = data[0];
				for (int j = 5; j < len; j++) {
					// (c != 'C' && c != 'N' && c != 'L' && c != 'D' && c != 'F'
					// && c !='B')
					if (jdbFields[j].getType() == 'N') {
						tmp[j] = new Integer(data[j - 3]);// 跨过名称代码
					} else if (jdbFields[j].getType() == 'F') {
						tmp[j] = new Float(data[j - 3]);// 跨过名称代码
					} else if (jdbFields[j].getType() == 'B') {
						tmp[j] = new Double(data[j - 3]);// 跨过名称代码
					} else if (jdbFields[j].getType() == 'C') {
						int fieldLen = jdbFields[j].getLength();
						if (fieldLen < data[j - 3].length()) {
							tmp[j] = data[j - 3].substring(0, fieldLen);
						} else {
							tmp[j] = data[j - 3];
						}

					} else if (jdbFields[j].getType() == 'D') {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
						try {
							tmp[j] = sdf.parse(data[j - 3]);// 跨过名称代码
						} catch (Exception ex) {
							ex.printStackTrace();
							tmp[j] = new java.util.Date();
						}
						// tmp[j] = new java.util.Date(data[j-3]);//跨过名称代码
					} else if (jdbFields[j].getType() == 'L') {
						tmp[j] = new Boolean(data[j - 3]);// 跨过名称代码
					} else {
						tmp[j] = data[j - 3];// 跨过名称代码
					}

				}
			}

			alist.add(tmp);
		}
		return alist;
	}

	public JDBField[] getField(String[] titles) throws ApplicationException {
		JDBField[] jdbFields = new JDBField[titles.length];
		String[] fields = null;
		for (int i = 0; i < titles.length; i++) {
			fields = new String[titles.length];
			fields = StringUtils.split(titles[i], ":");
			if (fields.length != 5) {
				throw new ApplicationException("导出公式DBF文件字段定义错误");
			}
			int len = 0, pri = 0;
			if (fields[3].equals("B") || fields[3].equals("F")) {
				len = Integer.parseInt(fields[4]) * 10 / 10;
				pri = Integer.parseInt(fields[4]) * 10 % 10;
			} else {
				len = Integer.parseInt(fields[4]);
			}
			try {
				jdbFields[i] = new JDBField(fields[2], fields[3].charAt(0),
						len, pri);
			} catch (Exception ex) {
				ex.printStackTrace();
				throw new ApplicationException(ex.getMessage());
			}
		}

		return jdbFields;
	}

	public static void writeFile(java.io.OutputStream out,
			JDBField[] jdbFields, ArrayList al) throws Exception {
		DBFWriter dbfwriter = new DBFWriter(out, jdbFields, "UTF-8");
		Object[] obj = null;
		for (int i = 0; i < al.size(); i++) {
			obj = (Object[]) al.get(i);
			dbfwriter.addRecord(obj);
		}
		// dbfwriter.close();
	}

	public static void writeFile(String fileName, JDBField[] jdbFields,
			ArrayList al) throws Exception {
		DBFWriter dbfwriter = new DBFWriter(fileName, jdbFields, "UTF-8");
		Object[] obj = null;
		for (int i = 0; i < al.size(); i++) {
			obj = (Object[]) al.get(i);
			dbfwriter.addRecord(obj);
		}
		dbfwriter.close();
	}

	public void writeIndicationData(OutputStream out, String fileType,
			String[] fieldName, StringBuffer str, String fileName, int specialOP) {
		try {
			ResultSet rs = null;
			if (fileType.equalsIgnoreCase("xls")) {
				WritableWorkbook workbook = Workbook.createWorkbook(out);
				WritableSheet sheet = workbook.createSheet("", 0);
				int i = 0;
				for (int j = 0; j < fieldName.length; j++) {
					Label label = new Label(j, i, fieldName[j]);
					sheet.addCell(label);
				}
				while (rs.next()) {
					i++;
					for (int j = 0; j < fieldName.length; j++) {
						Label label = new Label(j, i, rs
								.getString(fieldName[j]));
						sheet.addCell(label);
					}
				}
				workbook.write();
				workbook.close();
			} else {
				StringBuffer strB = new StringBuffer();
				for (int j = 0; j < fieldName.length; j++) {
					if (j > 0) {
						strB.append(",");
					}
					if (fileType.equalsIgnoreCase("csv")) {
						strB.append("\"" + fieldName[j] + "\"");
					} else {
						strB.append(fieldName[j]);
					}
				}
				strB.append("\r\n");
				try {
					out.write(strB.toString().getBytes());
				} catch (IOException e1) {
				}
				while (rs.next()) {
					strB = new StringBuffer();
					for (int j = 0; j < fieldName.length; j++) {
						if (j > 0) {
							strB.append(',');
						}
						if (fileType.equalsIgnoreCase("csv")) {
							strB.append("\"" + rs.getString(fieldName[j])
									+ "\"");
						} else {
							strB.append(rs.getString(fieldName[j]));
						}
					}
					strB.append("\r\n");
					try {
						out.write(strB.toString().getBytes());

					} catch (IOException e1) {
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// public static void main(String[] args) {
	// }
}
